﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;

namespace OperateWebcam
{
    public class VideoForWindows : IOperateWebcam
    {
        private CVideo video;
        private IntPtr handle;
        private int width;
        private int height;



        /// <summary>
        /// 无参构造函数
        /// </summary>
        private VideoForWindows()
        {
            this.handle = (IntPtr)0;
            this.width = 0;
            this.height = 0;
            this.video = new CVideo((IntPtr)0, 0, 0);
        }


        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="handle">控件句柄</param>
        /// <param name="width">图像宽度</param>
        /// <param name="height">图像高度</param>
        public VideoForWindows(IntPtr handle,int width,int height)
        {
            this.handle = handle;
            this.width = width;
            this.height = height;
            video = new CVideo(handle, width, height);
        }


        /// <summary>
        /// 打开视频
        /// </summary>
        public void Start()
        {
            video.StartWebCam();
        }


        /// <summary>
        /// 关闭视频
        /// </summary>
        public void Close()
        {
            video.CloseWebcam();
        }


        /// <summary>
        /// 将视频信息存为图片信息
        /// </summary>
        /// <param name="s">存储路径</param>
        public Bitmap Save(string path)
        {
            video.GrabImage(path);
            Bitmap curBitmap = video.GrabImage();
            return curBitmap;
        }

        /// <summary>
        /// 返回抓取图像
        /// </summary>
        /// <returns>抓取图像</returns>
        public Bitmap Grab(string path)
        {
            Bitmap curBitmap = video.GrabImage();
            byte thres = 50;
            curBitmap = BinaryImage(curBitmap,thres);
            // curBitmap.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
            return curBitmap;
        }

        /// <summary>
        /// 给定阈值法二值化模块
        /// </summary>
        /// <param name="b"></param>
        /// <param name="threshold"></param>
        /// <returns></returns>
        private Bitmap BinaryImage(Bitmap b, byte threshold)
        {
            int width = b.Width;
            int height = b.Height;
            BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            unsafe
            {
                byte* p = (byte*)data.Scan0;
                int offset = data.Stride - width * 4;
                byte R, G, B, gray;
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        R = p[2];
                        G = p[1];
                        B = p[0];
                        gray = (byte)((R * 19595 + G * 38469 + B * 7472) >> 16);
                        if (gray >= threshold)
                        {
                            p[0] = p[1] = p[2] = 255;
                        }
                        else
                        {
                            p[0] = p[1] = p[2] = 0;
                        }
                        p += 4;
                    }
                    p += offset;
                }
                b.UnlockBits(data);
                return b;
            }
        }

        /// <summary>
        /// Otsu阈值法二值化模块 
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        private Bitmap BinaryImage(Bitmap b)
        {
            // 图像灰度化   
            // b = Gray(b);   
            int width = b.Width;
            int height = b.Height;
            byte threshold = 0;
            int[] hist = new int[256];
            int AllPixelNumber = 0, PixelNumberSmall = 0, PixelNumberBig = 0;
            double MaxValue, AllSum = 0, SumSmall = 0, SumBig, ProbabilitySmall, ProbabilityBig, Probability;
            BitmapData data = b.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            unsafe
            {
                byte* p = (byte*)data.Scan0;
                int offset = data.Stride - width * 4;
                for (int j = 0; j < height; j++)
                {
                    for (int i = 0; i < width; i++)
                    {
                        hist[p[0]]++;
                        p += 4;
                    }
                    p += offset;
                }
                b.UnlockBits(data);
            }
            //计算灰度为I的像素出现的概率   
            for (int i = 0; i < 256; i++)
            {
                AllSum += i * hist[i];     //   质量矩   
                AllPixelNumber += hist[i];  //  质量       
            }
            MaxValue = -1.0;
            for (int i = 0; i < 256; i++)
            {
                PixelNumberSmall += hist[i];
                PixelNumberBig = AllPixelNumber - PixelNumberSmall;
                if (PixelNumberBig == 0)
                {
                    break;
                }
                SumSmall += i * hist[i];
                SumBig = AllSum - SumSmall;

                ProbabilitySmall = SumSmall / PixelNumberSmall;

                ProbabilityBig = SumBig / PixelNumberBig;

                Probability = PixelNumberSmall * ProbabilitySmall * ProbabilitySmall + PixelNumberBig * ProbabilityBig * ProbabilityBig;
                if (Probability > MaxValue)
                {
                    MaxValue = Probability;
                    threshold = (byte)i;
                }
            }
            return this.BinaryImage(b, threshold);
        } // end of OtsuThreshold 2  
    }
}
